//
//  PCCommentController.m
//  PhotoCircle
//
//  Created by GL on 15/12/20.
//  Copyright © 2015年 wujungao. All rights reserved.
//

#import "PCCommentController.h"
#import "PCCommentCell.h"
#import "PCUserModel.h"
#import "DXMessageToolBar.h"
#import "SVPullToRefresh.h"
#import "fetchData.h"
#import "NSDate+Convenience.h"
#import "PCcommentModel.h"
#import "PCUserLoginViewController.h"
#import "PCEditCommentController.h"
#import "GMPhotoView.h"

#define TAG_LoginAlertView  1111
#define TAG_DeleteImage   1112

@interface PCCommentController ()<UITableViewDataSource,UITableViewDelegate,DXMessageToolBarDelegate,PCCommentCellDelegate,UIAlertViewDelegate,PCEditCommentDelegate>
{
    BOOL _isRefresh;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) PCUserModel *userModel;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) PCCommentCell *dummyCell;
@property (strong, nonatomic) DXMessageToolBar *chatToolBar;
@property (strong, nonatomic) UIView *viewKeyBoardApp;//键盘出现时的背景View
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic, strong) GMPhotoView *photoView;


@end

@implementation PCCommentController

- (PCCommentCell *)dummyCell
{
    if (!_dummyCell) {
        static NSString *cellIdentifier = @"PCCommentCell";
        _dummyCell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    return _dummyCell;
}

-(PCUserModel *)userModel{
    _userModel = [[PCUserInfoManager sharedUserInfo] readUserInfo];
    return _userModel;
}
-(NSMutableArray*)dataArr{
    if (_dataArr == nil) {
        _dataArr = [[NSMutableArray alloc]init];
    }
    return _dataArr;
}
#pragma mark - 输入框
- (DXMessageToolBar *)chatToolBar
{
    if (_chatToolBar == nil) {
        _chatToolBar = [[DXMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - [DXMessageToolBar defaultHeight], self.view.frame.size.width, [DXMessageToolBar defaultHeight])];
        _chatToolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
        _chatToolBar.maxTextInputViewHeight = 82;
        _chatToolBar.delegate = self;
    }
    return _chatToolBar;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    
    MCHiddenBottomView();
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if (_isRefresh) {
        [self.tableView triggerPullToRefresh];
    }
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.5)];
    lineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    [self.view addSubview:lineView];
}

-(UIView*)headView{
    UIView *head = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10, 29.5, CGRectGetWidth(head.frame)-20, 0.5)];
    line.backgroundColor = PCColorC5;
    head.backgroundColor = [UIColor whiteColor];
    UILabel *commentLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 50, 30)];
    commentLab.font = [UIFont systemFontOfSize:12];
    commentLab.textColor = PCColorC4;
    commentLab.text = @"最新评论";
    UIView *redViewLine = [[UIView alloc]initWithFrame:CGRectMake(15, 29, 58, 1)];
    redViewLine.backgroundColor = PCColorC52;
    
    [head addSubview:line];
    [head addSubview:commentLab];
    [head addSubview:redViewLine];
    return head;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if (self.albumId == nil) {
        self.albumId = @"";
    }
    if (self.item_type == nil) {
         self.item_type = @"";
    }
    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor clearColor];
    
    [self.tableView setTableFooterView:view];
    self.tableView.tableHeaderView = [self headView];
    _isRefresh = NO;
    
    [self configUI];
    // Do any additional setup after loading the view.
}


-(void)configUI
{    
     self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan=NO;
    
    _pageIndex = 1;
    __weak PCCommentController *weakSelf = self;
    [self.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf toRefresh];
    }];
    [self.tableView addPullToRefreshWithTriggerHandler:^{
        [weakSelf toTrigger];
    }];
    
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf toLoadMore];
    }];
    
    [self.tableView triggerPullToRefresh];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshGameList) name:@"refreshCommentList" object:nil];

}

-(void)refreshGameList{
    [self.tableView triggerPullToRefresh];
}

- (void)tapViewToHiddenKeyBoard:(UITapGestureRecognizer *)tap{
    [self.chatToolBar.inputTextView resignFirstResponder];
}

-(void)toRefresh{
    
    _pageIndex = 1;
    __weak PCCommentController *weakSelf = self;
    NSNumber *page = [NSNumber numberWithInteger:_pageIndex];
    NSDictionary *pDic = nil;
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
            pDic = @{@"page":page,@"token":self.userModel.userToken,@"item_uuid":self.albumId,@"item_type":self.item_type};
    }else{
           pDic = @{@"page":page,@"item_uuid":self.albumId,@"item_type":self.item_type};
    }
   
    [[fetchData shared] getCommentDataWithPatameterDict:pDic sucessBlock:^(NSArray *commentArr) {
        _pageIndex++;
        [weakSelf.tableView.pullToRefreshView stopAnimating];
        [weakSelf.dataArr removeAllObjects];
        [weakSelf.dataArr addObjectsFromArray:commentArr];
        UserDefaults_SetObject([NSDate date], NSStringFromClass([self class]));//刷新时间保存
        [weakSelf.tableView reloadData];
    } otherCode:^(NSInteger code) {
        [weakSelf.tableView.pullToRefreshView stopAnimating];
    } failBlock:^{
        [weakSelf.tableView.pullToRefreshView stopAnimating];
    }];

}
-(void)toTrigger{
    
    NSString *lastUpdateTime = [UserDefaults_GetObject(NSStringFromClass([self class])) sinceNowDescription];
    if(!lastUpdateTime.length)
        lastUpdateTime = NSLocalizedString(STR_NeverRefresh, );
    NSString *lastUpdateStr = PCStrFormat(@"%@%@", NSLocalizedString(STR_LastAt, ), lastUpdateTime);
    [self.tableView.pullToRefreshView setSubtitle:lastUpdateStr forState:SVPullToRefreshStateAll];
}
-(void)toLoadMore{
    
    __weak PCCommentController *weakSelf = self;
    //NSNumber *page = [NSNumber numberWithInteger:_pageIndex];
    NSDictionary *pDic = nil;
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
        pDic = @{@"page":[NSString stringWithFormat:@"%ld",(long)_pageIndex],@"token":self.userModel.userToken,@"item_uuid":self.albumId,@"item_type":self.item_type};
    }else{
        pDic = @{@"page":[NSString stringWithFormat:@"%ld",(long)_pageIndex],@"item_uuid":self.albumId,@"item_type":self.item_type};
    }
   
    
    [[fetchData shared]getCommentDataWithPatameterDict:pDic sucessBlock:^(NSArray *commentArr) {
        [weakSelf.tableView.infiniteScrollingView stopAnimating];
        if (commentArr.count > 0) {
            _pageIndex++;
            [weakSelf.dataArr addObjectsFromArray:commentArr];
            [weakSelf.tableView reloadData];
        }else{
            // 没有数据
        }
    } otherCode:^(NSInteger code) {
        [weakSelf.tableView.infiniteScrollingView stopAnimating];
    } failBlock:^{
        [weakSelf.tableView.infiniteScrollingView stopAnimating];
        [GMTipsHelper showBadNetwork];
    }];

}
#pragma mark-
#pragma mark-网络，评论，点赞
/**
 *  评论
 *
 */
-(void)submitCommentWithStr:(NSString*)commentStr
{
    __weak PCCommentController *weakSelf = self;
    NSDictionary *pDic = nil;
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
        pDic = @{@"content":commentStr,@"token":self.userModel.userToken,@"item_uuid":self.albumId,@"item_type":self.item_type};
    }else{
        [self p_creatAlertViewWithShowLogin:0];
        return;
    }
     [GMTipsHelper showLoading];
//    [[fetchData shared] postSubmitCommentDataWithPatameterDic:pDic sucessBlock:^(PCCommentModel *myCommemtModel) {
//        [GMTipsHelper showDismiss];
//        if (myCommemtModel) {
//            
//            [weakSelf.dataArr insertObject:myCommemtModel atIndex:0];
//            [weakSelf.tableView reloadData];
//            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES   ];
//        }
//        [weakSelf clearTextView];
//    } otherCodeBlock:^(NSInteger code) {
//        
//        if (code == API_RESPONSE_INVALIDTOKEN) {
//            [GMTipsHelper showDismiss];
//            [weakSelf p_creatAlertViewWithShowLogin:1];
//        }else{
//            [GMTipsHelper showFail:[NSString stringWithFormat:@"error:%ld",code]];
//        }
//    } failWithBlock:^{
//        [GMTipsHelper showBadNetwork];
//    }];
}
-(void)clearTextView{
    self.chatToolBar.inputTextView.text = nil;
}
-(void)supportCommentWithUuid:(NSString*)uuid{
    
    __weak PCCommentController *weakSelf = self;
    NSDictionary *pDic =nil;
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
        pDic =  @{@"token":self.userModel.userToken,@"item_uuid":uuid,@"item_type":@"Comment"};
    }else{
        [self p_creatAlertViewWithShowLogin:0];
        return;
    }
    
    [[fetchData shared]postSupportDic:pDic sucessBlock:^{
        
    } otherCodeBlock:^(NSInteger code) {
        if (code == API_RESPONSE_INVALIDTOKEN) {
            [weakSelf p_creatAlertViewWithShowLogin:1];
        }
    } failWithBlock:^{
        
    }];
}
/**
 *  弹出登录对话框
 *
 *  @param login 登录？重复登录
 */
-(void)p_creatAlertViewWithShowLogin:(NSInteger)login
{
    NSString *tipMessage = nil;
    if (login == 0) {
        tipMessage = @"您未登录";
    }else{
        tipMessage = @"账号已在其它设备登陆，是否重新登录?";
    }
//    [MarkSingle sharedStore].isMySelfVC = YES;
//    [GMMarkSingle sharedStore].pushViewController = self;
    if (iOS(8.0)) {
        UIAlertController * deleteAlert = [UIAlertController alertControllerWithTitle:@"提示" message:tipMessage preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAciton = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self loginVc];
        }];
        
        UIAlertAction *cancleAcion = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [deleteAlert addAction:cancleAcion];
        [deleteAlert addAction:okAciton];
        [self presentViewController:deleteAlert animated:YES completion:^{
            
        }];
        
    }else{
        UIAlertView *loginAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:tipMessage delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消", @"登录", nil];
        loginAlert.delegate = self;
        loginAlert.tag = TAG_LoginAlertView;
        [loginAlert show];
    }
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == TAG_LoginAlertView ) {
        if (buttonIndex == 1) {
            [self loginVc];
        }
    }
}

-(void)loginVc{
    _isRefresh = YES;
    PCUserLoginViewController *logVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PCUserLoginVC"];
    [self.navigationController pushViewController:logVC animated:YES];
    
}
#pragma mark -
#pragma mark -NSNotificationCenter
- (void)hiddenKeyBoard:(NSNotificationCenter *)center{
    _viewKeyBoardApp.hidden = YES;
}
- (void)appearKeyBoard:(NSNotificationCenter *)center{
    _viewKeyBoardApp.hidden = NO;
}

#pragma mark -
#pragma mark - DXMessageToolBarDelegate输入框的代理方法
//开始输入
- (void)inputTextViewWillBeginEditing:(XHMessageTextView *)messageInputTextView{
    //    [self.chatToolBar hiddenSendLableAndSendImageView];
}
- (void)didChangeFrameToHeight:(CGFloat)toHeight{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.tableView.frame;
        rect.origin.y = 0;
        rect.size.height = self.view.frame.size.height - toHeight;
        self.tableView.frame = rect;
    }];
}

- (void)didSendText:(NSString *)text{
    
    [self.chatToolBar.inputTextView resignFirstResponder];
    if (text && text.length > 0) {
        [self.chatToolBar.inputTextView resignFirstResponder];
        [self submitCommentWithStr:text];//发送评论
    }else{
        [GMTipsHelper showFail:@"评论不能为空"];//提示发送文字为空
    }
}

#pragma mark -
#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *questionCellID = @"PCCommentCell";
    PCCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
    [cell configCellWithModel:self.dataArr[indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    GMCourseModel *course = self.courseArray[1][indexPath.row];
    [self.dummyCell configCellWithModel:self.dataArr[indexPath.row] ];
//    CGSize size = [self.dummyCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
//    
//    NSLog(@"gaodu:%f",size.height);
    float height = [self.dummyCell cellHeight];
    return height;
    //return 100;
}

#pragma mark -
#pragma mark - PCEditCommentDelegate
-(void)submitCommentSussecc{
    _isRefresh = YES;
}

-(void)thumbTapWithCellModel:(PCCommentModel *)model
{
    // 浏览大图
    _photoView = [[GMPhotoView alloc] initWithFrame:self.view.bounds andImageUrl:model.imageUrl];
    _photoView.alpha = 1.0;
}

#pragma mark-
#pragma mark-点赞
- (IBAction)goToComment:(UIButton *)sender {
    
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
        
        PCEditCommentController *editCommentVC = [self.storyboard instantiateViewControllerWithIdentifier:@"editCommentVC"];
        editCommentVC.albumId = self.albumId;
        editCommentVC.item_type = self.item_type;
        [self.navigationController pushViewController:editCommentVC animated:YES];

    }else{
        [self p_creatAlertViewWithShowLogin:0];
        return;
    }

}

-(void)likeButtonClickWithCellModel:(PCCommentModel *)model{
    
    [self supportCommentWithUuid:model.uuid];
}

- (IBAction)backEvent:(id)sender {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshCommentList" object:nil];

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
